package com.socket.nio.demo1;

import com.socket.nio.util.ByteBufferPrinter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Hexudong
 * @date 2025/4/5
 */
@Slf4j
public class Server {

  public static void main(String[] args) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(16);
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.bind(new InetSocketAddress(8082));

    // 连接集合
    List<SocketChannel> channelList = new ArrayList<>();
    while (true) {
      // 建立与客户端连接
      SocketChannel sc = ssc.accept();//阻塞方法
      channelList.add(sc);
      for (SocketChannel channel : channelList) {
        // 接收客户端发送的数据
        channel.read(buffer);
        buffer.flip();
        ByteBufferPrinter.prettyPrint(buffer);
        buffer.clear();
      }
    }
  }
}
